#include "DBService.h"

#include "NFComm/NFPluginLoader/NFCPluginManager.h"

IDBService *g_pDBService = NULL;

DBService::DBService()
{
	m_GetFileDataFun = nullptr;
	g_pDBService = this;
}

DBService::~DBService()
{
}

bool DBService::Init()
{
    std::string strCSVDir = "csv/";
    std::string strDBConfig = strCSVDir + "_index";
    std::vector<std::string> vecNames;
    int nTableCount = 0;


    std::string strContent;
    pPluginManager->GetFileContent(strDBConfig, strContent);
    unsigned char *pData = (unsigned char *)strContent.data();
    int nPos = 0;
    memcpy(&nTableCount, pData, sizeof(nTableCount));
    pData += sizeof(nTableCount);

    vecNames.resize(nTableCount);
    for (int i = 0; i < nTableCount; i++)
    {
        char cLength;
        char szName[255];

        memcpy(&cLength, pData, sizeof(cLength));
        pData += sizeof(cLength);

        memcpy(&szName, pData, cLength);
        pData += cLength;

        szName[cLength] = 0;
        vecNames[i] = szName;
    }

    free(pData);

    m_vecTables.resize(nTableCount, NULL);
    for (int i = 0; i < nTableCount; i++)
    {
        DBTable *pTable = new DBTable();

        pPluginManager->GetFileContent(strCSVDir + vecNames[i] + ".csv", strContent);

        if (pTable->LoadFromMemory((const char *)strContent.data(), strContent.size()))
        {
            pTable->MakeKey(0);
            m_vecTables[i] = pTable;
        }
        else
        {
            assert(0);
            delete pTable;
        }
    }
    return true;
}
bool DBService::Shut()
{
    return true;
}

bool DBService::ReadyExecute()
{
    return true;
}

bool DBService::Execute()
{
    return true;
}

bool DBService::AfterInit()
{
    return true;
}

DBTable *DBService::FindTable(int nType)
{
    return m_vecTables[nType];
}

DBRecord *DBService::FindRecord(int nType, int nID)
{
    return m_vecTables[nType]->FindRecord(nID);
}

DBRecord *DBService::FindRecord(int nType, const char *pKey)
{
    return m_vecTables[nType]->FindRecord(pKey);
}

IDBBlock *DBService::FindData(int nType, int nID)
{
	IDBRecord *pRecord = FindRecord(nType, nID);
	if(pRecord)
	{
		return pRecord->Block();
	}
	return NULL;
}

IDBBlock *DBService::FindData(int nType, const char *pKey)
{
	IDBRecord *pRecord = FindRecord(nType, pKey);
	if(pRecord)
	{
		return pRecord->Block();
	}
	return NULL;
}

void DBService::SetGetFileDataFun(GetFileDataFun fun)
{
	m_GetFileDataFun = fun;
}